package top.zerocn.main;

import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.Scanner;

import top.zerocn.dao.BookOperator;
import top.zerocn.entity.Book;

/**
 * 
 * @author Zero
 *
 */
public class App {

	private BookOperator bookOperator = new BookOperator();
	private Scanner in = new Scanner(System.in);
	private PrintStream out = System.out;

	public static void main(String[] args) {
		new App().mainMenu();
	}

	/**
	 * 主菜单
	 */
	public void mainMenu() {
		out.println("========== 欢迎使用图书管理系统 ==========");
		out.println("请输入：1、添加图书；2、查询图书；0、退出");

		do {
			int flg = 0;
			// 容错处理
			boolean repeat;
			do {
				try {
					flg = Integer.parseInt(in.next().trim());
					repeat = false;
				} catch (Exception e) {
					out.print("请输入正确的编号：");
					repeat = true;
				}
			} while (repeat);

			if (flg == 0) {
				out.println("********** 退出系统 **********");
				out.println("感谢您的使用！再见");
				System.exit(0);
			}
			if (flg == 1) {
				saveBook();
			}
			if (flg == 2) {
				getBook();
			}
			out.print("请输入对应编号：");
		} while (true);
	}

	/**
	 * 添加图书
	 */
	private void saveBook() {
		out.println("请输入书名：");
		String name = in.next().trim();

		if (bookOperator.getBook(name) != null) {
			out.println("已有该图书！！！请重新录入");
			saveBook();
		}

		BigDecimal price = null;
		String author = null;

		out.println("请输入价格：");
		boolean repeat;
		do {
			try {
				price = new BigDecimal(in.next().trim());
				repeat = false;
			} catch (Exception e) {
				out.print("请正确的价格：");
				repeat = true;
			}
		} while (repeat);

		out.println("请输入作者：");
		author = in.next().trim();

		boolean flg = bookOperator.saveBook(new Book(name, price, author));
		if (!flg) {
			out.println("添加失败！！！请重新录入");
			saveBook();
		}
		out.println("添加成功");

	}

	/**
	 * 查询图书
	 */
	private void getBook() {
		out.println("请输入书名：");
		Book book = bookOperator.getBook(in.next().trim());

		if (book == null) {
			out.println("未查询到该图书！");
			return;
		}

		out.println("图书名称：" + book.getName());
		out.println("图书价格：" + book.getPrice());
		out.println("图书作者：" + book.getAuthor());
	}
}
